package main.java.indi.zyj.sword;

public class WordPuzzle {

    public boolean wordPuzzle(char[][] grid, String target) {

        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return false;
        }

        int row = grid.length;
        int col = grid[0].length;

        char[] charArray = target.toCharArray();
        boolean[][] visited = new boolean[row][col];

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == charArray[0]) {
                    return dfs(grid, target, i, j, charArray, visited, 0);
                }
            }
        }

        return false;


    }

    private boolean dfs(char[][] board, String target, int i, int j, char[] chars, boolean[][] visited, int start) {
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length
                || chars[start] != board[i][j] || visited[i][j]) {
            return false;
        }
        if (start == chars.length - 1) {
            return true;
        }
        visited[i][j] = true;
        boolean ans = false;
        ans = dfs(board, target, i + 1, j, chars, visited, start + 1)
                || dfs(board, target, i - 1, j, chars, visited, start + 1)
                || dfs(board, target, i, j + 1, chars, visited, start + 1)
                || dfs(board, target, i, j - 1, chars, visited, start + 1);
        visited[i][j] = false;
        return ans;
    }

}
